<?php
/**
 * 基类（实现登录控制）
 * author: heimuya
 * time: 2014-4-15
 */
 namespace Admin\Controller;
 use Think\Controller;
 
class CommonController extends Controller {
	
	public function _initialize(){
		if(!isset($_SESSION[C('USER_AUTH_KEY')])){
			unset($_SESSION);
			session_destroy();
			//redirect(C('SC_ADMIN').'?s=Admin/Login');
			echo "<script>top.location.href='".U('login/index')."';</script>";
		}
	}
	
	
	/**
	 * 检查是否有相同排序号,有则替换，并整体往后启动一位
	 * @param $table 数据表
	 * @param $sequence 排序号
	 * @param $type 操作类型
	 * @param $id 原始Id
	 * @return $sid 返回可以插入的序列号
	 */
	 public function checkSequence($table, $sequence, $type = 'create', $id = null){
	 	$model = D($table);
		$existMaxSequence = $model->max('sequence');
		if($type == 'create'){//新增
			if(intval($sequence) > intval($existMaxSequence) || $sequence == '' || $sequence == null){//需要插入的序号大于最大的序号
				return intval($existMaxSequence) + 1;
			}
			//需要插入的序号在现存序号之间，则其后的都顺序加1
			$sequence = intval($sequence);
			$where['sequence'] = array('egt', $sequence);
			$model->where($where)->setInc('sequence');
		}else{
			$oldsequence = $model->field('sequence')->where('id = '.$id)->find();
			$oldsequence = intval($oldsequence['sequence']);
			$sequence = intval($sequence);
			if($type == 'edit'){
				if($oldsequence > $sequence){
					$where['sequence'] = array(array('egt', $sequence), array('lt', $oldsequence), 'and');
					$model->where($where)->setInc('sequence');
				}else{
					$where['sequence'] = array(array('gt', $oldsequence), array('elt', $sequence), 'and');
					$model->where($where)->setDec('sequence');
				}
			}else if($type == 'delete'){
				$where['sequence'] = array('gt', $oldsequence);
				$model->where($where)->setDec('sequence');
			}
		}
		return ($existMaxSequence > $sequence) ? $sequence : $existMaxSequence;
	 }
}
